package com.lewin.ringroad.net.message;

import io.netty.buffer.ByteBuf;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 排队长度
 *
 * @author Jun
 * @since 1.0.0
 */
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class QueueLengthMessage extends BaseMessage {
    //@formatter:off

    private byte checkChannelNumber;

    private List<ChannelData> channelDataList;

    //@formatter:on

    @Override
    public BaseMessage parse(ByteBuf buf) {
        this.checkChannelNumber = buf.readByte();
        this.channelDataList = new ArrayList<>(this.checkChannelNumber);
        for (int i = 0; i < this.checkChannelNumber; i++) {
            this.channelDataList.add(ChannelData.parseFrom(buf));
        }

        return this;
    }

    public float averageLen() {
        if (ObjectUtils.isEmpty(channelDataList)) {
            return 0;
        }
        return channelDataList.stream()
                .map(ChannelData::getLength)
                .reduce(Float::sum)
                .stream()
                .findFirst()
                .map(t -> t / channelDataList.size())
                .orElse(0f);
    }

    @Data
    public static class ChannelData {
        /**
         * 检测通道号
         */
        private short code;
        /**
         * 排队长度, 单位 m
         */
        private float length;

        private static ChannelData parseFrom(ByteBuf buf) {
            ChannelData data = new ChannelData();
            data.code = buf.readUnsignedByte();
            data.length = buf.readFloatLE();
            return data;
        }
    }
}
